package com.randao.manage.user.service;


import com.randao.api.community.RedisService;
import com.randao.framework.common.api.CommonResult;
import com.randao.framework.model.domain.user.UserInfo;
import com.randao.framework.utils.MD5Util;
import com.randao.framework.utils.TimerUtil;
import com.randao.manage.user.dao.UserManageMapper;
import com.randao.manage.user.utils.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Random;

/**
 * @Author： ~Mr·Weng~
 * @CreateTime： 2019年-04月-15日  18:11
 * Look at the wine in the glass toast the rich first.
 */
@Service
public class UserManagerService {


    @Autowired
    private UserManageMapper userManageMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisService redisService;

    @Value("${redis.key.prefix.authCode}")
    private String PREFIX_AUTHCODE;     //redis自定义的前缀

    @Value("${redis.key.expire.authCodeTime}")
    private Long EXPIRE_AUTHCODETIME;   //redis中验证码超时时间





    /**
     * 创建短信验证码
     *
     * @param phone
     */
    public String createSmsCode(final String phone) {
        //创建验证码
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        System.out.println("smscode = " + sb);

        //存储到redis中
        redisService.set(PREFIX_AUTHCODE + phone, sb.toString());
        System.out.println("验证码------->>>：验证码已经存入到redis中");
        //设置超时时间
        redisService.expire(PREFIX_AUTHCODE + phone, EXPIRE_AUTHCODETIME);
        System.out.println("验证码------->>>：redis中的验证已经设置了超时时间为90s");

        //调用倒计时工具类，记录验证码的时间
        TimerUtil.timer1s(90);



        //发送到消息中间件

        return sb.toString();
    }

    /**
     * 注册
     * @param uname
     * @param password
     * @param authCode
     * @return
     * @throws Exception
     */
    @Transactional
    public CommonResult userRegister(String uname, String password, String telephone, String authCode) throws Exception {

        //判断验证码是否正确
        if (!verifyAuthCode(telephone, authCode)) {
            return CommonResult.failed("验证码不正确");
        }

        //查询用户名存不存在
        List<UserInfo> userInfoList = userManageMapper.findByUname(uname);
        if (!CollectionUtils.isEmpty(userInfoList)) {
            return CommonResult.failed("该用户已经存在");
        }

        //加密后设置到userInfo对象
        String encodePasswoed = MD5Util.getEncryptedPwd(password);
        UserInfo userInfo = new UserInfo();
        userInfo.setPassword(encodePasswoed);
        userInfo.setUsername(uname);
        userInfo.setPhone(telephone);

        userManageMapper.userRegister(userInfo);
        userInfo.setPassword(null);
        return CommonResult.success(userInfo, "注册成功");

    }

    //判断验证码是否正确
    private boolean verifyAuthCode(String telephone, String authCode) {
        if (StringUtils.isEmpty(authCode)) {    //如果验证码为空
            return false;
        }
        String smsCode = redisService.get(PREFIX_AUTHCODE + telephone);
        System.out.println("判断验证码---->>从redis中取出验证码：" + smsCode);
        return smsCode.equals(authCode);
    }



    /**
     * 查询全部
     *
     * @return
     */
    public List<UserInfo> findAll() {
        return userManageMapper.findAll();
    }

    /**
     * 登陆
     *
     * @param uname
     * @param password
     * @return
     */
    public String loginUser(String uname, String password) throws Exception {
        //根据用户名查询出密码
        UserInfo userInfo = userManageMapper.loginUser(uname);
        System.out.println("数据库查询的加密过后的密码=============================================================:" + userInfo.getPassword());
        //密码解密
        boolean validPasswdResult = MD5Util.validPasswd(password, userInfo.getPassword());
        if (!validPasswdResult) {
            return null;
        }
        //生成tocken
        return jwtTokenUtil.generateToken(userInfo);

    }

    /**
     * 刷新tocken
     *
     * @param oldTocken
     */
    public String refreshTocken(String oldTocken) throws Exception {
        String tocken = oldTocken.substring(oldTocken.length());
        //判断是不是可以刷新的tocken
        if (jwtTokenUtil.canRefresh(tocken)) {
            //返回刷新过的tocken
            return jwtTokenUtil.refreshToken(tocken);
        }
        return null;
    }


    /**
     * 密码修改
     *
     * @param password
     */
    public void updatePassword(String password) {
        userManageMapper.updatePassword(password);
    }


}
